<template>
  <view class="detail-container">
    <!-- 教师基本信息卡片 -->
    <view class="teacher-card">
      <image class="teacher-avatar" :src="teacherInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
      <view class="teacher-info">
        <view class="teacher-header">
          <text class="teacher-name">{{ teacherInfo.name }}</text>
          <view class="certification-tag" v-if="teacherInfo.certificationStatus === 2">已认证</view>
        </view>
        <view class="teacher-subjects">擅长：{{ getSubjectText(teacherInfo.subjects) }}</view>
        <view class="teacher-exp">教龄：{{ teacherInfo.teachingAge || 0 }}年</view>
      </view>
    </view>

    <!-- 教师介绍 -->
    <view class="section">
      <view class="section-title">教师介绍</view>
      <view class="section-content">{{ teacherInfo.description || '暂无介绍' }}</view>
    </view>

    <!-- 课程信息 -->
    <view class="section">
      <view class="section-title">课程信息</view>
      <view v-if="teacherCourses.length > 0" class="course-list">
        <view
          class="course-item"
          :class="{ 'selected': selectedCourse && selectedCourse.id === course.id }"
          v-for="course in teacherCourses"
          :key="course.id"
          @tap="selectCourse(course)">
          <image class="course-image" :src="course.coverImage || '/static/default-course.png'" mode="aspectFill"></image>
          <view class="course-info">
            <text class="course-title">{{ course.title }}</text>
            <text class="course-desc" v-if="course.description">{{ course.description }}</text>
            <view class="course-price">
              <text class="price">¥{{ course.price }}</text>
              <text class="original-price" v-if="course.originalPrice">¥{{ course.originalPrice }}</text>
            </view>
          </view>
          <view class="course-select-indicator" v-if="selectedCourse && selectedCourse.id === course.id">
            <text class="select-icon">✓</text>
          </view>
        </view>
      </view>
      <view v-else class="empty-content">
        该教师暂无课程信息
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="selected-course-info" v-if="selectedCourse">
        <view class="selected-course-text">
          <text class="selected-label">已选择：</text>
          <text class="selected-title">{{ selectedCourse.title }}</text>
          <text class="selected-price">¥{{ selectedCourse.price }}</text>
        </view>
      </view>
      <view class="action-buttons">
        <button class="contact-btn" @tap="handleContact">联系老师</button>
        <button
          class="signup-btn"
          :class="{ 'disabled': !selectedCourse }"
          @tap="handleSignup">
          {{ selectedCourse ? '立即报名' : '请选择课程' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { courseApi, teacherApi } from '../../api';
import request from '@/utils/request';

export default {
  data() {
    return {
      teacherId: null,
      teacherPhone: null, // 添加教师手机号
      loading: false,
      teacherInfo: {
        name: '',
        avatar: '',
        subjects: [],
        teachingAge: 0,
        description: '',
        certificationStatus: 1,
        price: 100
      },
      teacherCourses: [],
      selectedCourse: null // 选中的课程
    }
  },
  
  onLoad(options) {
    console.log('教师详情页onLoad, 参数:', options);
    if (options.id) {
      this.teacherId = options.id;
      console.log('获取到教师ID:', this.teacherId);

      // 获取传入的手机号参数
      if (options.phone) {
        this.teacherPhone = decodeURIComponent(options.phone);
        console.log('获取到教师手机号:', this.teacherPhone);
      }

      this.getTeacherDetail();
    } else {
      console.error('未获取到教师ID');
      uni.showToast({
        title: '未获取到教师ID',
        icon: 'none'
      });
    }
  },
  
  methods: {
    async getTeacherDetail() {
      this.loading = true;
      uni.showLoading({
        title: '加载中...'
      });
      
      try {	
		const res = await teacherApi.getTeacherDetail(this.teacherId)
        console.log('教师详情数据:', res);
        if (res.code === 200) {
          this.teacherInfo = res.data;
          // 获取该教师的课程列表
		  console.log("开始查询教师课程列表")
          this.getTeacherCourses();
        } else {
          uni.showToast({
            title: res.message || '获取教师详情失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取教师详情失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    
    async getTeacherCourses() {
      try {
		  // 获取教师对应的课程列表
        // const res = await request({
        //   url: '/user/api/courses/teacher',
        //   method: 'GET',
        //   params: { teacherId: this.teacherId }
        // });
		const res = await courseApi.getTeacherCourse(this.teacherId)
        
        if (res.code === 200) {
          this.teacherCourses = res.data || [];
		  console.log("查询教师课程列表方法成功执行", this.teacherCourses);

          // 如果只有一个课程，自动选中
          if (this.teacherCourses.length === 1) {
            this.selectedCourse = this.teacherCourses[0];
            console.log('自动选中唯一课程:', this.selectedCourse.title);
          }
        }
      } catch (error) {
        console.error('获取教师课程失败:', error);
      }
    },
    
    getSubjectText(subjects) {
      if (!subjects || subjects.length === 0) return '暂无科目信息';
      return subjects.join('、');
    },
    
    handleContact() {
      // 如果有教师手机号，显示手机号并提供拨打选项
      if (this.teacherPhone) {
        // 检查当前平台是否支持拨打电话
        const platform = uni.getSystemInfoSync().platform;
        console.log('当前平台:', platform);

        uni.showModal({
          title: '联系老师',
          content: `教师手机号：${this.teacherPhone}\n\n是否拨打电话联系老师？`,
          confirmText: '拨打电话',
          cancelText: '复制号码',
          success: (res) => {
            if (res.confirm) {
              // 拨打电话
              uni.makePhoneCall({
                phoneNumber: this.teacherPhone,
                success: () => {
                  console.log('拨打电话成功');
                  uni.showToast({
                    title: '正在拨打电话',
                    icon: 'success'
                  });
                },
                fail: (err) => {
                  console.error('拨打电话失败:', err);
                  // 如果拨打失败，提供复制号码的选项
                  uni.showModal({
                    title: '拨打失败',
                    content: '无法拨打电话，是否复制手机号？',
                    confirmText: '复制号码',
                    cancelText: '取消',
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        this.copyPhoneNumber();
                      }
                    }
                  });
                }
              });
            } else if (res.cancel) {
              // 复制手机号到剪贴板
              this.copyPhoneNumber();
            }
          }
        });
      } else {
        // 没有手机号时提供多种联系方式选择
        uni.showActionSheet({
          itemList: ['在线客服', '留言咨询'],
          success: (res) => {
            if (res.tapIndex === 0) {
              // 跳转到AI客服聊天页面
              uni.navigateTo({
                url: '/pages/chat/index'
              });
            } else if (res.tapIndex === 1) {
              // 显示留言提示
              uni.showToast({
                title: '留言功能开发中',
                icon: 'none'
              });
            }
          }
        });
      }
    },

    // 复制手机号到剪贴板
    copyPhoneNumber() {
      uni.setClipboardData({
        data: this.teacherPhone,
        success: () => {
          uni.showToast({
            title: '手机号已复制',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('复制失败:', err);
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 选择课程
    selectCourse(course) {
      console.log('选择课程:', course);
      this.selectedCourse = course;

      // 提供触觉反馈
      uni.vibrateShort();

      // 显示选择提示
      uni.showToast({
        title: `已选择：${course.title}`,
        icon: 'success',
        duration: 1500
      });
    },

    handleSignup() {
      // 检查是否选择了课程
      if (!this.selectedCourse) {
        uni.showToast({
          title: '请先选择要报名的课程',
          icon: 'none'
        });
        return;
      }

      // 使用选中的课程信息进行报名
      const course = this.selectedCourse;
      const courseId = course.id;
      const price = course.price || 100;
      const title = course.title || '';
      const coverImage = course.coverImage || '';

      console.log('准备报名课程:', {courseId, title, price, teacherId: this.teacherId});

      uni.navigateTo({
        url: `/pages/signup/signup?teacherId=${this.teacherId}&courseId=${courseId}&price=${price}&courseTitle=${encodeURIComponent(title)}&coverImage=${encodeURIComponent(coverImage)}`
      });
    }
  }
}
</script>

<style>
.detail-container {
  padding: 20rpx;
  padding-bottom: 120rpx; /* 为底部操作栏留出空间 */
  background-color: #f5f5f5;
}

.teacher-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  display: flex;
  margin-bottom: 20rpx;
}

.teacher-avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  margin-right: 30rpx;
}

.teacher-info {
  flex: 1;
}

.teacher-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.teacher-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-right: 20rpx;
  
}

.certification-tag {
  background: #4080FF;
  color: #fff;
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.teacher-subjects {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.teacher-exp {
  font-size: 28rpx;
  color: #666;
}

.section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.section-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.empty-content {
  font-size: 28rpx;
  color: #999;
  text-align: center;
  padding: 40rpx 0;
}

.course-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.course-item {
  background: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.course-item:active {
  transform: scale(0.98);
}

.course-item.selected {
  background: #e3f2fd;
  border-color: #2196f3;
  box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.2);
}

.course-image {
  width: 100%;
  height: 180rpx;
  background: #f5f5f5;
}

.course-info {
  padding: 16rpx;
}

.course-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  font-weight: bold;
}

.course-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-price {
  display: flex;
  align-items: baseline;
}

.price {
  font-size: 32rpx;
  color: #E02E24;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 12rpx;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-buttons {
  display: flex;
  justify-content: space-between;
}

.contact-btn, .signup-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 30rpx;
  margin: 0 10rpx;
}

.contact-btn {
  background: #fff;
  color: #E02E24;
  border: 1rpx solid #E02E24;
  transition: all 0.3s ease;
}

.contact-btn:active {
  background: #FFF0EF;
  transform: scale(0.98);
}

.signup-btn {
  background: #E02E24;
  color: #fff;
  transition: all 0.3s ease;
}

.signup-btn:active {
  background: #C02620;
  transform: scale(0.98);
}

/* 禁用状态 */
.signup-btn.disabled {
  background: #ccc;
  color: #999;
}

.signup-btn.disabled:active {
  background: #ccc;
  transform: none;
}

/* 课程选择相关样式 */
.course-select-indicator {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 48rpx;
  height: 48rpx;
  background: #2196f3;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.select-icon {
  color: white;
  font-size: 28rpx;
  font-weight: bold;
}

.selected-course-info {
  margin-bottom: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border-left: 4rpx solid #2196f3;
}

.selected-course-text {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12rpx;
}

.selected-label {
  font-size: 24rpx;
  color: #666;
}

.selected-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  flex: 1;
}

.selected-price {
  font-size: 32rpx;
  color: #2196f3;
  font-weight: bold;
}

/* PC端悬停效果 */
/* #ifdef H5 */
.contact-btn:hover {
  background: #FFF0EF;
  cursor: pointer;
}

.signup-btn:hover {
  background: #C02620;
  cursor: pointer;
}

.signup-btn.disabled:hover {
  background: #ccc;
  cursor: not-allowed;
}

.course-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
}
/* #endif */
</style>